package no.hib.quiz;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class QuizListFragment extends Fragment{
	
	private View aView;

	public void onActivityCreated(Bundle savedInstanceState) {
	    super.onActivityCreated(savedInstanceState);
	
	}
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        // Inflate the layout for this fragment
		aView = inflater.inflate(R.layout.quiz_list, container, false);

		if (MainActivity.quizList.isEmpty() != true) {
			String quizListString = "";
			for (int i=0; i<MainActivity.quizList.size(); i++) {
				quizListString += (i+1) + ". " + MainActivity.quizList.get(i).getName() + "\n";
			}
			
			TextView tv = (TextView) aView.findViewById(R.id.tv_quiz_list);
			tv.setText(quizListString);
		
			Button btnStartQuiz =(Button)aView.findViewById(R.id.btn_start);
		    btnStartQuiz.setOnClickListener(new OnClickListener() {
	
		        @Override
		        public void onClick(View v) {
		        	
		        	EditText et = (EditText) aView.findViewById(R.id.et_quiz_number);
		        	String quizNrString = et.getText().toString();
		        	if (quizNrString.trim().length() > 0) {
		        		int quizNr = Integer.parseInt(quizNrString);
		        		if (quizNr > 0 && quizNr <= MainActivity.quizList.size() ) {
		        			MainActivity.quizNumber = (quizNr-1);
		        			
		        			FragmentManager fragmentManager = getFragmentManager();
		    	            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
	
		    	            TakeQuizFragment takeQuiz = new TakeQuizFragment();
		    	            fragmentTransaction.replace(R.id.fragment_container, takeQuiz);
		    	            fragmentTransaction.addToBackStack(null);
		    	            fragmentTransaction.commit();
		        		}
		        		else {
		        			et.setHint("Invalid quiz number");
		        		}
		        	}
		
		        }
		    });
		}
	
    	return aView;
		
	}
}

